#pragma

#include <iostream>
#include <memory>
#include <sys/epoll.h>
#include "nocopy.hpp"
#include "Epoll.hpp"
#include "Log.hpp"
#include "Socket.hpp"
using namespace std;

uint32_t EVENT_IN = (EPOLLIN);
uint32_t EVENT_OUT = (EPOLLOUT);

class EpollServer:public nocopy
{
static const int num=64;
public:
    EpollServer(uint16_t port)
        : _port(port),
          listsock_ptr(new Sock()),
          epoll_ptr(new Epoller())
    {
    }
    void Acceptr()
    {
        string clientip;
        uint16_t clientport;
        int sock = listsock_ptr->Accept(&clientip, &clientport);
        if (sock > 0)
        {
            epoll_ptr->EpollUpdate(EPOLL_CTL_ADD,sock, EVENT_IN);
            lg(Info, "client get a new link,client@ %s:%d", clientip.c_str(), clientport);
        }
    }
    void Dispatcher(struct epoll_event recv[], int num)
    {
        for (int i = 0; i < num; i++)
        {
            uint32_t event = recv[i].events;
            int fd = recv[i].data.fd;
            if (event & EVENT_IN)
            {
                if (fd == listsock_ptr->Fd())
                {
                    Acceptr();
                }
                else
                {
                    Recver(fd);
                }
            }
        }
    }

    void Recver(int fd)
    {
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "get a message:" << buffer << endl;
            string echo_str = "server echo $";
            write(fd, echo_str.c_str(), echo_str.size());
        }
        else if (n == 0)
        {
            lg(Info, "client quit,close fd: %d", fd);
            epoll_ptr->EpollUpdate(EPOLL_CTL_ADD, fd, 0);
            close(fd);
        }
        else
        {
            lg(Warning, "recv error: fd is:%d", fd);
            epoll_ptr->EpollUpdate(EPOLL_CTL_ADD, fd, 0);
            close(fd);
        }
    }
    void Init()
    {
        listsock_ptr->Socket();
        listsock_ptr->Bind(_port);
        listsock_ptr->Listen();
        lg(Info, "create listen socket success:%d\n", listsock_ptr->Fd());
    }
    void Start()
    {
        epoll_ptr->EpollUpdate(EPOLL_CTL_ADD, listsock_ptr->Fd(), EVENT_IN);
        struct epoll_event rev[num];
        for (;;)
        {
            int n = epoll_ptr->EpolerWait(rev, num);
            if (n > 0)
            {
                lg(Debug, "event happened,fd is: %d", rev[0].data.fd);
                Dispatcher(rev,n);
            }
            else if (n == 0)
            {
                lg(Info, "time out...");
            }
            else
            {
                lg(Error, "epoll wait error");
            }
        }
    }

private:
    
    uint16_t _port;
    std::shared_ptr<Epoller> epoll_ptr;
    shared_ptr<Sock> listsock_ptr;
};